'use client'
import React, { useEffect, useState } from "react";
import {
  Spinner,
  Chip,
  Switch,
  Navbar,
  NavbarBrand,
  NavbarContent,
  Avatar,
  Tooltip,
  Divider,
} from "@nextui-org/react";
import { MdPreview } from "md-editor-rt";
import 'md-editor-rt/lib/style.css';
import { MoonIcon, SunIcon } from "@nextui-org/shared-icons";
import { FiClock, FiUser } from "react-icons/fi";
import dayjs from "dayjs";
import CommentSection from "@/app/components/comment/CommentSection";
import createAxiosClient from "@/app/utils/axiosRequest";

const request = createAxiosClient();

/**
 * 根据用户ID获取用户信息
 * @param {number} userId 用户ID
 * @returns 用户信息
 */
async function getUserById(userId: number) {
  try {
    const response = await request.get(`/app/user/${userId}`);
    if (response.data && response.data.code === 200) {
      return response.data.data;
    }
    return null;
  } catch (error) {
    console.error("获取用户信息失败:", error);
    return null;
  }
}

export default function ShareView({ params }: { params: { shareId: string } }) {
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [noteData, setNoteData] = useState<any>(null);
  const [authorData, setAuthorData] = useState<any>(null);
  const [isDarkMode, setIsDarkMode] = useState(false);

  useEffect(() => {
    // 获取分享笔记数据
    async function fetchSharedNote() {
      try {
        setIsLoading(true);
        const response = await request.get(`/app/share/${params.shareId}`);
        console.log("分享笔记响应:", response);

        if (response.data && response.data.code === 200) {
          setNoteData(response.data.data);
          document.title = `${response.data.data.title} - 分享笔记`;
          
          // 如果有用户ID，获取分享者信息
          if (response.data.data.userId) {
            const userData = await getUserById(response.data.data.userId);
            setAuthorData(userData);
          }
        } else {
          setError(response.data?.message || "获取分享笔记失败");
        }
      } catch (err: any) {
        console.error("获取分享笔记错误:", err);
        setError(err.response?.data?.message || "获取分享笔记时发生错误");
      } finally {
        setIsLoading(false);
      }
    }

    fetchSharedNote();
  }, [params.shareId]);

  // 格式化日期
  const formatDate = (date: string | null) => {
    if (!date) return "未知时间";
    return dayjs(date).format("YYYY-MM-DD HH:mm");
  };

  // 切换主题模式
  const toggleDarkMode = () => {
    setIsDarkMode(!isDarkMode);
  };

  return (
    <div className={isDarkMode ? "dark" : "light"}>
      <div className="min-h-screen bg-gray-50 dark:bg-gray-800 flex flex-col">
        {/* 顶部导航栏 */}
        <Navbar
          isBordered
          className="bg-background/80 dark:bg-gray-800/80 backdrop-blur-md"
          maxWidth="full"
        >
          <NavbarBrand>
            {noteData && (
              <div className="flex items-center">
                {noteData.emoji && (
                  <span className="mr-2 text-xl dark:text-white">{noteData.emoji}</span>
                )}
                <p className="font-bold text-inherit text-lg line-clamp-1 dark:text-white">
                  {noteData?.title || "分享笔记"}
                </p>
              </div>
            )}
          </NavbarBrand>
          <NavbarContent justify="end">
            <Switch
              size="sm"
              color="secondary"
              isSelected={isDarkMode}
              onValueChange={toggleDarkMode}
              thumbIcon={({ isSelected, className }) =>
                isSelected ? <MoonIcon className={className} /> : <SunIcon className={className} />
              }
            />
          </NavbarContent>
        </Navbar>

        {/* 主要内容区域 */}
        <div className="flex-grow flex justify-center">
          {isLoading ? (
            <div className="flex justify-center items-center h-full w-full">
              <Spinner label="加载中..." color="primary" />
            </div>
          ) : error ? (
            <div className="flex justify-center items-center h-full w-full">
              <div className="p-6 bg-white dark:bg-gray-900 rounded-lg shadow max-w-lg mx-auto my-8 text-center">
                <h2 className="text-xl font-semibold text-red-500 mb-2">出错了</h2>
                <p className="text-gray-700 dark:text-gray-300">{error}</p>
              </div>
            </div>
          ) : (
            <div className="w-full max-w-4xl px-4 py-6 mx-auto">
              {/* 笔记信息和分享者信息 */}
              <div className="bg-white dark:bg-gray-900 rounded-t-lg p-6 shadow mb-0">
                {/* 分享者信息 */}
                {authorData && (
                  <div className="mb-4 flex items-center">
                    <Avatar 
                      src={authorData.avatar || "https://i.pravatar.cc/150?img=3"}
                      size="md"
                      className="mr-3"
                    />
                    <div>
                      <p className="font-medium dark:text-white">
                        {authorData.nickname || authorData.username}
                      </p>
                      <p className="text-xs text-gray-500 dark:text-gray-400">
                        分享于: {formatDate(noteData.createdAt || noteData.updatedAt)}
                      </p>
                    </div>
                  </div>
                )}
                
                <Divider className="my-3" />
                
                <div className="flex items-center flex-wrap gap-2 mb-4">
                  <Chip
                    startContent={<FiClock size={14} />}
                    variant="flat"
                    size="sm"
                    color="secondary"
                    className="dark:text-white"
                  >
                    更新于: {formatDate(noteData.updatedAt)}
                  </Chip>
                  {noteData.viewCount > 0 && (
                    <Chip
                      variant="flat"
                      size="sm"
                      color="primary"
                      className="dark:text-white"
                    >
                      阅读: {noteData.viewCount}
                    </Chip>
                  )}
                </div>

                {/* 标签显示 */}
                {noteData.tags && noteData.tags.length > 0 && (
                  <div className="flex flex-wrap gap-2 mt-3">
                    {noteData.tags.map((tag: any) => (
                      <Chip
                        key={tag.id}
                        variant="flat"
                        size="sm"
                        color="default"
                        className="bg-gray-100 dark:bg-gray-700 dark:text-white"
                      >
                        {tag.name}
                      </Chip>
                    ))}
                  </div>
                )}
              </div>

              {/* 笔记内容 */}
              <div className="bg-white dark:bg-gray-900 rounded-b-lg p-4 md:p-6 shadow mb-6">
                <div className="markdown-body dark:text-white">
                  <MdPreview
                    modelValue={noteData.content}
                    previewTheme={"github"}
                    showCodeRowNumber
                    theme={isDarkMode ? "dark" : "light"}
                    className="dark:text-white"
                  />
                </div>
              </div>

              {/* 评论区域 */}
              <div className="mt-6">
                {noteData && <CommentSection noteId={noteData.id} />}
              </div>
            </div>
          )}
        </div>

        {/* 底部信息 */}
        <footer className="bg-white dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700 py-4 text-center text-sm text-gray-500 dark:text-gray-400">
          © {new Date().getFullYear()} Me Notes - 分享更有价值
        </footer>
      </div>
    </div>
  );
}